package com.qf.shiro2202day02.shiroconfig;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.shiro2202day02.user.entity.User;
import com.qf.shiro2202day02.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义Realm，用于实现查询用户身份信息和权限信息
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 获取当前登录用户的身份信息
        // 对象类型取决于 doGetAuthenticationInfo 中返回的 AuthenticationInfo 对象中的 第一参数
        final User user = (User) principals.getPrimaryPrincipal();

        // 查询用户的角色信息
        List<String> roles = getRoleFromDb(user);

        // 查询户的权限信息
        List<String> permissions = getPermissionFromDb(user);

        final SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        simpleAuthorizationInfo.addRoles(roles);

        simpleAuthorizationInfo.addStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }

    private List<String> getPermissionFromDb(User user) {

//        List<String> pessions =  userService.getPermission(user);
        List<String> pessions =  userService.getPermissionBysql(user);

        return pessions;
    }

    private List<String> getRoleFromDb(User user) {

//        List<String> roles = userService.getUserRole(user);

        List<String> roles = userService.getUserRoleBySql(user);

        return roles;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        // 获取用户名
        final String username = (String) token.getPrincipal();

        // 根据用户名查询数据库，得到user对象
        User user = getUserFromDB(username);

        if (user==null){
            throw new UnknownAccountException();
        }

        final SimpleAuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(user,
                        user.getPassword(),
                        ByteSource.Util.bytes(user.getSalt()),    // 盐的处理
                        this.getName());

        return authenticationInfo;
    }

    private User getUserFromDB(String username) {

        final QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        userQueryWrapper.eq("username",username);

        final User user = userService.getOne(userQueryWrapper);

        return user;
    }
}
